<template>
  <el-dialog :close-on-click-modal='false' :title="record.Index ? $t('编辑') : $t('添加')" :v-if="dialogVisible" v-drag :visible.sync="dialogVisible" width="600px" top="10vh" @close='close'>
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" :label-width="lang === 'zh'?'80px':'130px'" :rules="rules" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('隧道名称')" prop="TunnelName">
          <el-input v-emoji v-model="record.TunnelName" ref="tunnelName" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('共享秘钥')" prop="PreSharedKey">
          <el-input v-emoji v-model="record.PreSharedKey" ref="preSharedKey" :placeholder="$t('共享秘钥必须为16位！')" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('协议类型')" prop="IpType">
          <el-select v-model="record.IpType" :placeholder="$t('请选择')" ref="ipType" size='small' :disabled='record.Index ? true : false'>
            <el-option v-for="(value, key) in ipTypeList" :key="key" :label="value" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane :label="$t('本端配置')" name="local" size="small">
            <el-form-item :label="$t('本端IP')" prop="LocalIp">
              <el-input v-emoji v-model="record.LocalIp" ref="localIp" style="width:215px;" size="small"></el-input>
              <el-button type="success" @click="add_addr('LocalIp')" size="small" class="addClick1">{{$t('添加')}}</el-button>
            </el-form-item>
            <div>
              <el-table size='mini' :data="record.LocalIpv4Net" style="width: 100%">
                <el-table-column prop='Ipv4Net' align='center' :label="$t('子网')">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.Ipv4Net" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop='Netmask' align='center' :label="record.IpType === 'v4' ? $t('子网掩码') : $t('前缀长度')">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.Netmask" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" align='center' :label="$t('操作')" width="120">
                  <template slot-scope="scope">
                    <el-button @click="deleteRow(scope.$index, record.LocalIpv4Net, scope.row)" type="danger" plain size="mini" :class="'del' + (scope.$index + 1)">
                      {{$t('删除')}}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="$t('远端配置')" name="remote" size="small">
            <el-form-item :label="$t('远端IP')" prop="RemoteIp">
              <el-input v-emoji v-model="record.RemoteIp" ref="remoteIp" style="width:215px;" size="small"></el-input>
              <el-button type="success" @click="add_addr('RemoteIp')" size="small" class="addClick2">{{$t('添加')}}</el-button>
            </el-form-item>
            <div>
              <el-table size='mini' :data="record.RemoteIpv4Net" style="width: 100%">
                <el-table-column prop='Ipv4Net' align='center' :label="$t('子网')">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.Ipv4Net" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop='Netmask' align='center' :label="record.IpType === 'v4' ? $t('子网掩码') : $t('前缀长度')">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.Netmask" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" align='center' :label="$t('操作')" width="120">
                  <template slot-scope="scope">
                    <el-button @click="deleteRow(scope.$index, record.RemoteIpv4Net, scope.row)" type="danger" plain size="mini" :class="'del' + (scope.$index + 1)">
                      {{$t('删除')}}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <addIpDialog ref="refAddIpDialog" v-if="addIpDialogVisible" @ipSubmit='ipSubmit' @getInfoRefresh='getInfoRefresh'></addIpDialog>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addInfo, getInfo, editInfo } from '@/api/network/ipsecvpn' //  delLocalNetwork, delRemoteNetwork,
import addIpDialog from './addIpDialog'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'ipsecvpnDialog',
  components: {
    addIpDialog
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validatePreSharedKey = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (value.length !== 16) {
        callback(new Error(this.$t('密钥必须设置为16个字符')))
      } else {
        callback()
      }
    }
    var validateIp = (rule, value, callback) => {
      if (String(value).trim() === '') {
        if (this.activeName === 'local' && rule.field === 'RemoteIp') {
          this.$messages.error(this.$t('远端配置IP不能为空'))
        } else if (this.activeName === 'remote' && rule.field === 'LocalIp') {
          this.$messages.error(this.$t('本端配置IP不能为空'))
        }
        callback(new Error(this.$t('不能为空')))
      } else if (this.record.IpType === 'v4' && !this.isValidIP(value)) {
        if (this.activeName === 'local' && rule.field === 'RemoteIp') {
          this.$messages.error(this.$t('远端配置IP格式输入错误!'))
        } else if (this.activeName === 'remote' && rule.field === 'LocalIp') {
          this.$messages.error(this.$t('本端配置IP格式输入错误!'))
        }
        callback(new Error(this.$t('请输入正确的IP地址')))
      } else if (this.record.IpType === 'v6' && !this.isValidIPv6(value)) {
        if (this.activeName === 'local' && rule.field === 'RemoteIp') {
          this.$messages.error(this.$t('远端配置IP格式输入错误!'))
        } else if (this.activeName === 'remote' && rule.field === 'LocalIp') {
          this.$messages.error(this.$t('本端配置IP格式输入错误!'))
        }
        callback(new Error(this.$t('请输入正确的IP地址')))
      } else {
        callback()
      }
    }
    return {
      activeName: 'local',
      dialogVisible: false,
      addIpDialogVisible: false,
      old_LocalIp: [],
      old_RemoteIp: [],
      record: {
        Index: null,
        LocalIp: '',
        IpType: 'v4',
        LocalIpv4Net: [],
        PreSharedKey: '',
        RemoteIp: '',
        RemoteIpv4Net: [],
        TunnelName: '',
        TunnelOpenOrClose: '',
        TunnelStatus: '',
        IpIsChange: 0
      },
      recordCopy: {
        Index: null,
        LocalIp: '',
        IpType: 'v4',
        LocalIpv4Net: [],
        PreSharedKey: '',
        RemoteIp: '',
        RemoteIpv4Net: [],
        TunnelName: '',
        TunnelOpenOrClose: '',
        TunnelStatus: '',
        IpIsChange: 0
      },
      ipTypeList: {
        'v4': 'IPV4',
        'v6': 'IPV6'
      },
      lang: this.$i18n.locale,
      rules: {
        TunnelName: [{ required: false, validator: validateName, trigger: 'blur' }],
        PreSharedKey: [{ required: false, validator: validatePreSharedKey, trigger: 'blur' }],
        LocalIp: [{ required: false, validator: validateIp, trigger: 'blur' }],
        RemoteIp: [{ required: false, validator: validateIp, trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleClick (tab, event) {
      this.activeName = tab.name
    },
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['tunnelName', 'preSharedKey', 'localIp', 'remoteIp']
        const selectData = ['ipType']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
      })
      if (data) {
        this.record = Object.assign(this.record, data)
        this.old_LocalIp = this.record.LocalIp
        this.old_RemoteIp = this.record.RemoteIp
        if (this.isValidIP(this.record.LocalIp)) {
          this.record.IpType = 'v4'
        } else if (this.isValidIPv6(this.record.LocalIp)) {
          this.record.IpType = 'v6'
        }
        data.LocalIpNet.forEach(item => {
          this.record.LocalIpv4Net.push({ Ipv4Net: item.IpNet, Netmask: item.Netmask, lipIndex: item.lipIndex })
        })
        data.RemoteIpNet.forEach(item => {
          this.record.RemoteIpv4Net.push({ Ipv4Net: item.IpNet, Netmask: item.Netmask, ripIndex: item.ripIndex })
        })
      }
    },
    submit () {
      // 验证参数
      this.$refs.form.validate((valid) => {
        if (valid) {
          for (let item of this.record.LocalIpv4Net) {
            if (this.record.IpType === 'v4' && !this.isValidIP(item.Ipv4Net)) {
              this.$messages.error(this.$t('本地IP格式输入错误!'))
              return
            } else if (this.record.IpType === 'v6' && !this.isValidIPv6(item.Ipv4Net)) {
              this.$messages.error(this.$t('本地IP格式输入错误!'))
              return
            }
          }
          for (let item of this.record.RemoteIpv4Net) {
            if (this.record.IpType === 'v4' && !this.isValidIP(item.Ipv4Net)) {
              this.$messages.error(this.$t('远端IP格式输入错误!'))
              return
            } else if (this.record.IpType === 'v6' && !this.isValidIPv6(item.Ipv4Net)) {
              this.$messages.error(this.$t('远端IP格式输入错误!'))
              return
            }
          }
          let formData = JSON.parse(JSON.stringify(this.record))
          formData.LocalIpv4Net = JSON.stringify(formData.LocalIpv4Net)
          formData.RemoteIpv4Net = JSON.stringify(formData.RemoteIpv4Net)
          formData.IpIsChange = (formData.LocalIp !== this.old_LocalIp || formData.RemoteIp !== this.old_RemoteIp) ? 1 : 0
          if (this.record.Index) {
            editInfo(formData).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('编辑成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          } else {
            addInfo(formData).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('添加成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    close () {
      this.record = Object.assign({}, this.recordCopy)
      this.record.LocalIpv4Net = []
      this.record.RemoteIpv4Net = []
      this.old_LocalIp = []
      this.old_RemoteIp = []
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },
    ipSubmit (data, type) {
      if (type === 'LocalIp') {
        this.record.LocalIpv4Net.push(data)
      } else {
        this.record.RemoteIpv4Net.push(data)
      }
      this.soltArray()
    },
    add_addr (type) {
      this.$refs.form.validateField(type, (valid) => {
        if (!valid) {
          this.addIpDialogVisible = true
          this.$nextTick(() => {
            this.$refs.refAddIpDialog.init(type, this.record.Index, this.record.IpType)
          })
        }
      })
    },
    deleteRow (index, form, row) {
      // if (this.record.Index) {
      //   if (this.activeName === 'local') {
      //     delLocalNetwork({ Index: this.record.Index, lipIndex: row.lipIndex }).then(res => {
      //       if (res.status === 0) {
      //         this.$message({
      //           message: this.$t('删除成功'),
      //           type: 'success'
      //         })
      //         this.getInfoRefresh()
      //       }
      //     })
      //   } else {
      //     delRemoteNetwork({ Index: this.record.Index, ripIndex: row.ripIndex }).then(res => {
      //       if (res.status === 0) {
      //         this.$message({
      //           message: this.$t('删除成功'),
      //           type: 'success'
      //         })
      //         this.getInfoRefresh()
      //       }
      //     })
      //   }
      // } else {
      form.splice(index, 1)
      // }
    },
    soltArray () {
      this.record.LocalIpv4Net.forEach((item, index) => {
        item.lipIndex = index
      })
      this.record.RemoteIpv4Net.forEach((item, index) => {
        item.ripIndex = index
      })
    },
    getInfoRefresh () {
      getInfo({ id: this.record.Index }).then(res => {
        if (res.status === 0) {
          this.record = Object.assign(this.record, res.info[0])
          if (res.info[0].LocalIpNet && res.info[0].LocalIpNet.length > 0) {
            this.record.LocalIpv4Net = []
            res.info[0].LocalIpNet.forEach(item => {
              this.record.LocalIpv4Net.push({ Ipv4Net: item.IpNet, Netmask: item.Netmask, ripIndex: item.ripIndex })
            })
          }
          if (res.info[0].RemoteIpNet && res.info[0].RemoteIpNet.length > 0) {
            this.record.RemoteIpv4Net = []
            res.info[0].RemoteIpNet.forEach(item => {
              this.record.RemoteIpv4Net.push({ Ipv4Net: item.IpNet, Netmask: item.Netmask, ripIndex: item.ripIndex })
            })
          }
          this.$parent.listData()
        }
      })
    },
    // 验证ipv4
    isValidIP (ip) {
      let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      return reg.test(ip)
    },
    // 验证ipv6
    isValidIPv6 (ip) {
      let reg = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A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,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?\s*$/
      return reg.test(ip)
    }
  }
}
</script>
